package znet

import (
	"bytes"
	"encoding/binary"
	"errors"
	"zinx/utils"
	"zinx/ziface"
)

type Datapack struct{}

func NewDatapack() *Datapack {
	return &Datapack{}
}

func (dp *Datapack) GetHeadLen() uint32 {
	//Datalen uint32(4字节) + ID uint32(4字节)
	return 8
}

func (dp *Datapack) Pack(msg ziface.IMessage) ([]byte, error) {
	//创建一个字节缓冲区
	dataBuff := bytes.NewBuffer([]byte{})
	//将dataLen写入buff
	if err := binary.Write(dataBuff, binary.LittleEndian, msg.GetMsgLen()); err != nil {
		return nil, err
	}
	//将msgId写入buff
	if err := binary.Write(dataBuff, binary.LittleEndian, msg.GetMsgId()); err != nil {
		return nil, err
	}
	//将data写入buff
	if err := binary.Write(dataBuff, binary.LittleEndian, msg.GetData()); err != nil {
		return nil, err
	}
	return dataBuff.Bytes(), nil
}

func (dp *Datapack) Unpack(binaryData []byte) (ziface.IMessage, error) {
	//创建一个从二进制数据流读取数据的Reader
	reader := bytes.NewReader(binaryData)
	//仅解压head信息，得到dataLen和msgId
	msg := &Message{}
	//读dataLen
	if err := binary.Read(reader, binary.LittleEndian, &msg.DataLen); err != nil {
		return nil, err
	}
	//读msgId
	if err := binary.Read(reader, binary.LittleEndian, &msg.Id); err != nil {
		return nil, err
	}
	//判断dataLen是否已经超出了限制最大包长度
	if utils.GlobalObject.MaxPackageSize > 0 && msg.DataLen > utils.GlobalObject.MaxPackageSize {
		return nil, errors.New("too large msg data recv")
	}
	return msg, nil
}
